import 'package:dio/dio.dart';
import '../http/dio_instance.dart';
import '../sample/configure/constants.dart';
import '../utils/LogUtils.dart';
import '../utils/constants.dart';
import '../utils/persistent_storage.dart';
import '../utils/sp_utils.dart';
import 'datas/ShareListdata.dart';
import 'datas/TangeEqData.dart';
import 'datas/TangeEqEent.dart';
import 'datas/TangeEqFilter.dart';
import 'datas/TangeEqTime.dart';
import 'datas/deviceBasicinfo.dart';
import 'datas/log_keys_data.dart';
import 'datas/onlineInfo.dart';

class TangeEqListResult {
  final List<TangeEqData>? tangeeqlist;
  final int? total;

  TangeEqListResult({this.tangeeqlist, this.total});
}

// 事件参数
class TangeEventListResult {
  final List<TangeEqEent>? tangeeventlist;
  final int? total;

  TangeEventListResult({this.tangeeventlist, this.total});
}

class Api {
  static Api instance = Api._();

  Api._();

  //探鸽 - 获取设备列表
  // Future<TangeEqListResult> gettangeeqList({required int pageNum,required int pageSize}) async {
  //   DioInstance.instance().changeBaseUrl("https://openapi-cn01.tange365.com/");
  //
  //   String? savedAccessToken = await SharedPreferencesUtil.instance
  //       .getString(SampleConstants.storageKeyLoginToken);
  //
  //   // LogUtils.d(savedAccessToken);
  //   // 添加请求头
  //   Map<String, dynamic> headers = {
  //     'Authorization': "${savedAccessToken}", // 替换为你的token
  //     'Content-Type': 'application/json', // 确保Content-Type为application/json
  //     'x-tg-app-id': '7886600',
  //     'accept-language': 'zh-CN',
  //     'x-tg-platform': 'web',
  //     'x-tg-sdk-version': '1024'
  //   };
  //
  //   // 将参数以JSON格式传递
  //   Map<String, dynamic> body = {
  //     "uuid": "",
  //     "device_id": "",
  //     "limit": pageSize,
  //     "name": "",
  //     "offset": pageNum
  //   };
  //
  //   Response response = await DioInstance.instance().post(
  //     path: "/v2/device/list",
  //     options: Options(headers: headers), // 将请求头添加到options中
  //     data: body, // 将参数以JSON格式传递
  //   );
  //   // LogUtils.d(response.data);
  //   // 解析items数组数据
  //   TangeEqKeyData data = TangeEqKeyData.fromJson(response.data);
  //   DioInstance.instance().changeBaseUrl("http://192.168.34.155:1024");
  //   // print(homeData.topList);
  //   // if (data.keyList != null) {
  //   //   for (var item in data.keyList!) {
  //   //     LogUtils.d("device_id: ${item.deviceId}, device_name: ${item.deviceName}, product_key: ${item.productKey}");
  //   //   }
  //   // }
  //   LogUtils.w(data.total);
  //   return TangeEqListResult(tangeeqlist: data.keyList, total: data.total);
  // }

  //探鸽 - 获取筛选条件
  Future<List<TangeEqFilter>?> gettangeeqfilterList(
      {required String? eqid}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {"deviceId": eqid};

    Response response = await DioInstance.instance().post(
      path: "/device/cloudFilter", // 将请求头添加到options中
      data: body, // 将参数以JSON格式传递
    );
    // LogUtils.d(response.data);
    // 解析items数组数据
    TangeEqFilterKeyData data = TangeEqFilterKeyData.fromJson(response.data);
    // print(homeData.topList);
    // if (data.keyList != null) {
    //   for (var item in data.keyList!) {
    //     LogUtils.d("device_id: ${item.deviceId}, device_name: ${item.deviceName}, product_key: ${item.productKey}");
    //   }
    // }
    return data.keyList;
  }

  // 设备列表
  Future<TangeEqListResult> gettangeeqList(
      {required int pageNum, required int pageSize}) async {
    // showToast("=1=执行请求======${DioInstance.instance()}====");
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {"pageSize": pageSize, "pageNum": pageNum};

    Response response = await DioInstance.instance().post(
      path: "/device/getMyList",
      data: body, // 将参数以JSON格式传递
    );
    // LogUtils.d(response.data);
    // showToast("=2=请求成功====>${response.data}");
    // 解析items数组数据
    TangeEqKeyData data = TangeEqKeyData.fromJson(response.data);
    // showToast("=3=解析数据>${data.total}");

    // LogUtils.w(data.total);
    return TangeEqListResult(tangeeqlist: data.keyList, total: data.total);
  }

  // 添加设备成功-同步设备数量
  Future<dynamic> equaldata({required String ID}) async {
    Response response =
        await DioInstance.instance().get(path: "/device/bind/${ID}");
    return response.data;
  }

  // 获取设备时区
  Future<dynamic> eqtimedata({required String ID}) async {
    Map<String, dynamic> body = {
      // 用户名
      "deviceId": ID,
    };
    Response response =
        await DioInstance.instance().post(path: "/device/deviceTz", data: body);
    // LogUtils.w(response);
    return TangeEqTime.fromJson(response.data);
  }

  // 注销用户 - 未同步
  Future<dynamic> unsubscribe() async {
    String userId = await SpUtils.getString(Constants.SP_USER_ID);

    Map<String, dynamic> headers = {
      'Content-Type': 'application/json',
    };

    int userIdInt = int.parse(userId);

    List<int> body = [userIdInt];

    Response response = await DioInstance.instance().post(
        path: "/employee/update/batch/delete",
        options: Options(headers: headers),
        data: body);
    return response.data;
  }

  // 删除设备（探鸽）
  Future<dynamic> equnbundle({String? deviceid}) async {
    Response response =
        await DioInstance.instance().get(path: "/device/unBind/$deviceid");
    return response.data;
  }

  // 获取设备封面
  Future<dynamic> eqcoverimg({required String deviceid}) async {
    Map<String, dynamic> body = {
      "deviceId": deviceid,
    };

    Response response = await DioInstance.instance().post(
      path: "/device/getCoverImage",
      data: body,
    );
    return response.data;
  }

  // 更新设备-是否录像
  // state状态(0：关闭；1：开启)
  Future<dynamic> equploadrecord(
      {required String ID, required String state}) async {
    Map<String, dynamic> body = {"id": ID, "state": state};

    Response response = await DioInstance.instance().post(
      path: "/device/update",
      data: body,
    );
    return response.data;
  }



  //探鸽 - 获取筛选条件
  // tag 事件类型
  // device_id 设备id
  // offset 页码
  // limit 页数
  // date 时间
  Future<List<TangeEqFilter>?> gettangeeqEventList(
      {required String? date,
      required String? id,
      required String? tag,
      required int? offset,
      required int? limit}) async {
    DioInstance.instance().changeBaseUrl("http://192.168.34.155:1024");

    String? savedAccessToken = await SharedPreferencesUtil.instance
        .getString(SampleConstants.storageKeyLoginToken);

    LogUtils.d(savedAccessToken);
    // 添加请求头
    Map<String, dynamic> headers = {
      'Authorization': "${savedAccessToken}", // 替换为你的token
      'Content-Type': 'application/json', // 确保Content-Type为application/json
      'x-tg-app-id': '7886600',
      'accept-language': 'zh-CN',
      'x-tg-platform': 'web',
      'x-tg-sdk-version': '1024'
    };

    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      "date": date,
      "device_id": id,
      "tag": ["${tag}"],
      "offset": offset,
      "limit": 2
    };

    Response response = await DioInstance.instance().post(
      path: "/v2/cloud/event",
      options: Options(headers: headers), // 将请求头添加到options中
      data: body, // 将参数以JSON格式传递
    );
    LogUtils.d(response.data);
    // 解析items数组数据
    TangeEqFilterKeyData data = TangeEqFilterKeyData.fromJson(response.data);
    DioInstance.instance().changeBaseUrl("http://192.168.34.155:1024");
    return data.keyList;
  }

  // 事件列表
  Future<TangeEventListResult> geteventList(
      {required int offset,
      required int limit,
      required String tag,
      required String date,
      required String deviceid}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      "date": date,
      "offset": offset,
      "limit": limit
    };

    if (deviceid.isNotEmpty) {
      body["deviceId"] = deviceid;
    }

    if (tag.isNotEmpty) {
      body["tag"] = ["${tag}"];
    }

    Response response = await DioInstance.instance().post(
      path: "/device/cloudEvent",
      data: body, // 将参数以JSON格式传递
    );
    // LogUtils.d(response.data);
    // 解析items数组数据
    TangeEventKeyData data = TangeEventKeyData.fromJson(response.data);

    LogUtils.w(data.total);
    return TangeEventListResult(
        tangeeventlist: data.keyList, total: data.total);
  }

  // 设备基础信息
  Future<dynamic> eqbasicdata({String? id}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      "deviceId": id,
    };

    Response response = await DioInstance.instance()
        .post(path: "/device/deviceBasicInfo", data: body);
    return DeviceBasicinfo.fromJson(response.data);
  }

  // 查询设备是否可升级
  Future<dynamic> equpgradePost({String? id}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      "deviceId": id,
    };

    Response response = await DioInstance.instance()
        .post(path: "/device/upgradePost", data: body);
    return DeviceBasicinfo.fromJson(response.data);
  }

  // 修改设备名称
  Future<dynamic> eqsavetitle({String? id, String? name}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      // 原密码
      "deviceId": id,
      // 新密码
      "deviceName": name
    };

    Response response = await DioInstance.instance()
        .post(path: "/device/updateName", data: body);
    return response.data;
  }

  // 重置密码 - 验证码重置
  Future<dynamic> usercodepassword ({String? username, String? password}) async {
    Map<String, dynamic> body = {
      // 用户名
      "loginName": username,
      "password": password
    };

    Response response = await DioInstance.instance()
        .post(path: "/login/updatePassword", data: body);
    LogUtils.d(response.data);

    return response.data;
  }

  // 获取验证吗
  Future<dynamic> usergetcode ({String? phone}) async {
    Map<String, dynamic> body = {
      // 用户名
      "phone": phone,
    };

    Response response = await DioInstance.instance()
        .post(path: "/login/getSmsCode", data: body);
    LogUtils.d(response.data);

    return response.data;
  }


  // 获取验证码注册
  Future<dynamic> userregistergetcode ({String? phone}) async {
    Map<String, dynamic> body = {
      // 用户名
      "phone": phone,
    };

    Response response = await DioInstance.instance()
        .post(path: "/login/getRegCode", data: body);
    LogUtils.d(response.data);

    return response.data;
  }


  // 验证验证码是否正确
  Future<dynamic> usergetsave ({String? phone,String? code}) async {
    Map<String, dynamic> body = {
      // 用户名
      "phone":phone,
      "code": code
    };

    Response response = await DioInstance.instance()
        .post(path: "/login/checkSmsCode", data: body);
    LogUtils.d(response.data);

    return response.data;
  }

  // 查询设备在线状态
  Future<dynamic> eqonlineInfo({String? deviceid}) async {
    Map<String, dynamic> body = {
      // 用户名
      "deviceId": deviceid,
    };

    Response response = await DioInstance.instance()
        .post(path: "/device/onlineInfo", data: body);
    LogUtils.d(response.data);

    return OnlineInfo.fromJson(response.data);
  }

  // 发送设备固件升级指令
  Future<dynamic> eqfirmwareup({String? id, String? version}) async {
    Map<String, dynamic> body = {
      // 用户名
      "deviceId": id,
      "version": version
    };

    Response response =
        await DioInstance.instance().post(path: "/device/upgrade", data: body);
    LogUtils.d(response.data);

    return OnlineInfo.fromJson(response.data);
  }

  // 注册-添加人员
  Future<dynamic> register(
      {String? accout, String? username, String? password}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      // 用户名
      "actualName": "智慧视联",
      // 验证码
      "code": username,
      // 部门id
      "departmentId": 1,
      // 是否启用 0-启用 1-不启用
      "disabledFlag": 0,
      // 邮箱 - 可写死
      "email": "999",
      // 性别 - 0-未知
      "gender": 0,
      // 不知
      "leaveFlag": 0,
      // 用户名 - 登录账号的
      "loginName": accout,
      // 手机号
      "phone": accout,
      // 密码
      "password": password
    };

    Response response =
        // await DioInstance.instance().post(path: "/employee/add", data: body);
        await DioInstance.instance()
            .post(path: "/employee/register", data: body);
    return response.data;
  }

  // 修改密码
  Future<dynamic> savepass({String? oldPassword, String? newPassword}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      // 原密码
      "oldPassword": oldPassword,
      // 新密码
      "newPassword": newPassword
    };

    Response response = await DioInstance.instance()
        .post(path: "/employee/update/password", data: body);

    return response;
  }

  // 登录
  Future<dynamic> login({String? name, String? password}) async {
    LogUtils.w(name);
    LogUtils.w(password);

    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      "captchaCode": "999",
      "captchaUuid": "999",
      "loginDevice": 3,
      "loginName": name,
      "password": password
    };

    Response response =
        await DioInstance.instance().post(path: "/login", data: body);
    return LogKeysData.fromJson(response.data);
    // return response.data;
  }

  // 修改用户名称
  Future<dynamic> saveusername({String? username}) async {
    String accout = await SpUtils.getString(Constants.SP_USER_PHONE);
    String userId = await SpUtils.getString(Constants.SP_USER_ID);
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      // 用户名
      "actualName": username,
      // 部门id
      "departmentId": 1,
      // 是否启用 0-启用 1-不启用
      "disabledFlag": 0,
      // 邮箱 - 可写死
      "email": "3026341569@qq.com",
      // 性别 - 0-未知
      "gender": 0,
      // 不知
      "leaveFlag": 0,
      // 用户名 - 登录账号的
      "loginName": accout,
      // 手机号
      "phone": accout,
      // 用户id
      "employeeId": userId
    };

    Response response =
        await DioInstance.instance().post(path: "/employee/update", data: body);
    return response.data;
  }

  // 分享列表
  Future<List<ShareListdata>?> getshareList({required String ID}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      "pageSize": 30,
      "pageNum": 1,
      "deviceId": ID,
    };

    Response response = await DioInstance.instance().post(
      path: "/device/shareList",
      data: body, // 将参数以JSON格式传递
    );
    // LogUtils.d(response.data);
    // 解析items数组数据
    ShareKeyListdata data = ShareKeyListdata.fromJson(response.data);

    // LogUtils.w(data.total);
    return data.KeyList;
  }

  // 操作分享
  Future<dynamic> getsaveshare(
      {required String? ID, required String? username}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      // 主键id
      "deviceId": ID,
      // 用户明
      "loginName": username
    };

    Response response =
        await DioInstance.instance().post(path: "/device/share", data: body);
    return response.data;
  }

  // 删除分享
  Future<dynamic> getdeleteshare({String? ID, String? UserId}) async {
    // 将参数以JSON格式传递
    Map<String, dynamic> body = {
      // 主键id
      "deviceId": ID,
      // 被删除id
      "userId": UserId
    };

    Response response =
        await DioInstance.instance().post(path: "/device/delShare", data: body);
    return response.data;
  }

  // 被分配用户-拒绝分享-主键id
  Future<dynamic> gettrunshare({String? deviceid}) async {
    Response response =
        await DioInstance.instance().get(path: "/device/delShare/$deviceid");
    return response.data;
  }
}
